package network.TCP.conversation;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author zxl
 * @version 1.0
 * @date 2021/10/22 9:15
 * 服务端
 */
public class Server {

    private static ByteArrayOutputStream baos;
    private static InputStream inputStream;
    private static ServerSocket serverSocket;
    private static Socket socket;

    public static void main(String[] args) {
        try {
            //有个地址
            serverSocket = new ServerSocket(9999);
            while (true){
                //等待客服端的连接 获得客户端的连接socket  阻塞式，一直监听客服端
                socket = serverSocket.accept();
                inputStream = socket.getInputStream();
                //缓冲流
                baos = new ByteArrayOutputStream();
                byte[] bytes = new byte[1024];
                int len;
                while ((len = inputStream.read(bytes)) != -1) {
                    baos.write(bytes, 0, len);
                }
                System.out.println(baos);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //释放资源
            if (baos != null) {
                try {
                    baos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (serverSocket != null) {
                try {
                    serverSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
